package com.my.mvvmrapid.ui.login;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.my.mvvmrapid.R;
import com.my.mvvmrapid.data.http.UserDataSourceImpl;
import com.my.mvvmrapid.data.http.retrofit.Rxjava2Manage;
import com.my.mvvmrapid.entity.LoginBean;
import com.my.mvvmrapid.entity.WanEntity;
import com.my.mvvmrapid.ui.main.MainActivity;
import com.tencent.mmkv.MMKV;
import com.zhongjh.mvvmrapid.base.viewmodel.BaseViewModel;
import com.zhongjh.mvvmrapid.binding.command.BindingCommand;
import com.zhongjh.mvvmrapid.bus.event.SingleLiveEvent;
import com.zhongjh.mvvmrapid.utils.ToastUtils;

import java.util.Objects;

import static com.my.mvvmrapid.data.local.MMKVLocal.PASS_WORD;
import static com.my.mvvmrapid.data.local.MMKVLocal.USER_NAME;

/**
 *
 * @author zhongjh
 * @date 2021/3/25
 */
public class LoginViewModel extends BaseViewModel {

    private static final int PASSWORD_LENGTH = 6;

    UserDataSourceImpl mUserDataSourceImpl = new UserDataSourceImpl();
    /**
     * 当前显示的布局id,start是登录界面，end是注册界面
     */
    int completedId = R.id.start;
    /**
     * 动画状态
     */
    public ObservableField<Integer> mTransitionToState = new ObservableField<>(R.id.start);
    /**
     * 登录界面用户名的绑定
     */
    public ObservableField<String> mUserNameLogin = new ObservableField<>("");
    /**
     * 登录界面密码的绑定
     */
    public ObservableField<String> mPasswordLogin = new ObservableField<>("");
    /**
     * 注册界面用户名的绑定
     */
    public ObservableField<String> mUserNameRegion = new ObservableField<>("");
    /**
     * 注册界面密码的绑定
     */
    public ObservableField<String> mPasswordRegion = new ObservableField<>("");
    /**
     * 注册界面二次密码的绑定
     */
    public ObservableField<String> mRePasswordRegion = new ObservableField<>("");

    /**
     * 界面发生改变的观察者
     */
    public UiChangeObservable mUiChange = new UiChangeObservable();

    /**
     * 通知UI事件
     */
    public static class UiChangeObservable {
        // 登录界面的账号错误
        public SingleLiveEvent<String> userNameLoginError = new SingleLiveEvent<>();

        public SingleLiveEvent<String> passwordLoginError = new SingleLiveEvent<>();

        public SingleLiveEvent<String> userNameRegionError = new SingleLiveEvent<>();

        public SingleLiveEvent<String> passwordRegionError = new SingleLiveEvent<>();

        public SingleLiveEvent<String> rePasswordRegionError = new SingleLiveEvent<>();

        // 登录中
        public SingleLiveEvent<Void> showLoginProgress = new SingleLiveEvent<>();
        // 登录成功
        public SingleLiveEvent<Void> showLoginSucceed = new SingleLiveEvent<>();
        // 登录异常
        public SingleLiveEvent<Void> showLoginError = new SingleLiveEvent<>();

    }

    public LoginViewModel(@NonNull Application application) {
        super(application);
    }

    // region ---------------- 事件----------------

    /**
     * MotionLayout转换登录或者注册事件,记录当前登录/注册面板id
     */
    public BindingCommand<Integer> onTransitionCompleted = new BindingCommand<>((currentId) -> completedId = currentId);

    /**
     * 点击登录面板，展示登录界面
     */
    public BindingCommand<Void> onClickViewLogin = new BindingCommand<>(() -> {
        if (completedId == R.id.end) {
            mTransitionToState.set(R.id.start);
        }
    });

    /**
     * 登录按钮的点击事件
     */
    public BindingCommand<Void> onClickTvLogin = new BindingCommand<>(() -> {
        if (completedId == R.id.end) {
            mTransitionToState.set(R.id.start);
        } else {
            // 判断长度
            if (Objects.requireNonNull(mUserNameLogin.get()).length() < PASSWORD_LENGTH) {
                // 通知ui
                mUiChange.userNameLoginError.setValue("账号长度需要超过6位");
                return;
            }
            if (Objects.requireNonNull(mPasswordLogin.get()).length() < PASSWORD_LENGTH) {
                mUiChange.passwordLoginError.setValue("密码长度需要超过6位");
                return;
            }
            // 进行登录
            Rxjava2Manage.simplifyConnection(mUserDataSourceImpl.login(mUserNameLogin.get(), mPasswordLogin.get()), this,
                    disposable -> {
                        // 显示等待动画
                        mUiChange.showLoginProgress.call();
                        // 關閉觸屏
                        closeTouching();
                    },
                    new Rxjava2Manage.CustomObserver<LoginBean>() {
                        @Override
                        public void onNext(WanEntity<LoginBean> loginBeanWanEntity) {
                            openTouching();
                            mUiChange.showLoginSucceed.call();
                            // 保存账号密码
                            MMKV kv = MMKV.defaultMMKV();
                            if (kv != null) {
                                kv.encode(USER_NAME, mUserNameLogin.get());
                                kv.encode(PASS_WORD, mPasswordLogin.get());
                            }
                            // 进入DemoActivity页面
                            startActivity(MainActivity.class);
                            // 关闭页面
                            finish();
                        }

                        @Override
                        public void onComplete() {
                            super.onComplete();
                        }

                        @Override
                        public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                            openTouching();
                            mUiChange.showLoginError.call();
                            super.onError(e);
                        }

                        @Override
                        public void onBusinessError(WanEntity<LoginBean> t) {
                            openTouching();
                            mUiChange.showLoginError.call();
                            super.onBusinessError(t);
                        }
                    });
        }
    });

    /**
     * 点击注册面板，展示注册界面
     */
    public BindingCommand<Void> onClickViewRegion = new BindingCommand<>(() -> {
        if (completedId == R.id.start) {
            mTransitionToState.set(R.id.end);
        }
    });

    /**
     * 点击注册字眼
     */
    public BindingCommand<Void> onClickTvRegion = new BindingCommand<>(() -> {
        if (completedId == R.id.start) {
            mTransitionToState.set(R.id.end);
        } else {
            // 判断长度
            if (Objects.requireNonNull(mUserNameRegion.get()).length() < PASSWORD_LENGTH) {
                // 通知ui
                mUiChange.userNameRegionError.setValue("账号长度需要超过6位");
                return;
            }
            if (Objects.requireNonNull(mPasswordRegion.get()).length() < PASSWORD_LENGTH) {
                mUiChange.passwordRegionError.setValue("密码长度需要超过6位");
                return;
            }
            if (Objects.requireNonNull(mRePasswordRegion.get()).length() < PASSWORD_LENGTH) {
                mUiChange.rePasswordRegionError.setValue("密码长度需要超过6位");
                return;
            }

            // 进行注册
            Rxjava2Manage.simplifyConnection(mUserDataSourceImpl.register(mUserNameRegion.get(), mPasswordRegion.get(), mRePasswordRegion.get()), this,
                    disposable -> {
                        // 關閉觸屏
                        closeTouching();
                    },
                    new Rxjava2Manage.CustomObserver<LoginBean>() {
                        @Override
                        public void onNext(WanEntity<LoginBean> loginBeanWanEntity) {
                            // 关闭等待动画并開啓觸屏
                            ToastUtils.showLong("注册成功");
                            mUserNameRegion.set("");
                            mPasswordRegion.set("");
                            mRePasswordRegion.set("");
                            openTouching();
                        }

                        @Override
                        public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                            super.onError(e);
                            openTouching();
                        }

                        @Override
                        public void onBusinessError(WanEntity<LoginBean> t) {
                            super.onBusinessError(t);
                            // 关闭等待动画并開啓觸屏
                            mTransitionToState.set(R.id.end);
                            openTouching();
                        }
                    });
        }
    });

    // endregion ---------------- 事件----------------

}
